// index.js
import { createRouter, createWebHistory } from 'vue-router'
import { homeRoutes } from './modules/home'
import { blogRoutes } from './modules/blog'
import { userMenuListStore } from '@/store/index'
const router = createRouter({
  // history: createWebHistory(import.meta.env.BASE_URL),
  history: createWebHistory(),
  routes: [
    {
      path: '',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        requiresAuth: false, // 页面无需登录
      },
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('@/views/layout/index.vue'),
      children: [
        ...homeRoutes,
        ...blogRoutes,
        // {
        //   path: '/',
        //   component: () => import('@/views/layout/main.vue'),
        //   children: [],
        //   meta: {
        //     requiredPermission: 'admin',
        //     requiresAuth: true,
        //   },
        // },
        {
          path: '/advert/index',
          component: () => import('@/views/advert/index.vue'),
          meta: { requiredPermission: 'admin' },
        },
      ],
    },
  ],
})

// 添加导航守卫
router.beforeEach(async (to, from, next) => {
  console.log(to, 'tooo')
  const isAuthenticated = localStorage.getItem('token')
  const store = userMenuListStore()
  if (to.meta.requiresAuth && !isAuthenticated) {
    // 要求身份验证但用户未经身份验证
    next('/login')
  } else if (!to.meta.requiresAuth) {
    // 页面无需登录
    next()
  } else {
    // 身份验证通过，继续导航
    // store.is_admin === 'admin' ? store.getMenuListStore() : store.getMenuListStoreVip()
    let res = ''
    console.log('验证通过了----------', store.is_admin)
    if (store.is_admin === 'admin') {
      res = await store.getMenuListStore()
    } else {
      res = await store.getMenuListStoreVip()
    }
    if (res != '') next()
  }
})

export default router
